package cn.cms.util;

import cn.cms.constants.Constants;
import cn.cms.model.SysUser;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

public class SessionUtil {

    /**
     * session 浏览器不动作失效时间设置
     */
    private static final int SESSION_MAX_AGE = 2 * 60 * 60;

    /**
     * 往session中存放登录信息
     *
     * @param request
     */
    public static void setAttribute(HttpServletRequest request, SysUser user) {
        HttpSession session = request.getSession(true);
        session.setAttribute("loginUser", user);
        session.setMaxInactiveInterval(SESSION_MAX_AGE);
    }

    /**
     * 往session中存放登录信息
     *
     * @param request
     */
    public static void setAttribute(HttpServletRequest request, String key, SysUser user) {
        HttpSession session = request.getSession(true);
        session.setAttribute(key, user);
        session.setMaxInactiveInterval(SESSION_MAX_AGE);
    }

    /**
     * 从session中获取信息
     *
     * @param request
     * @param key
     * @return
     */
    public static Object getAttribute(HttpServletRequest request, Serializable key) {

        HttpSession session = request.getSession(false);

        return session.getAttribute(key.toString());
    }


    /**
     * 往session中存放信息
     *
     * @param request
     * @param key
     * @param value
     */
    public static void setAttribute(HttpServletRequest request, String key, Object value) {

        HttpSession session = request.getSession(true);
        session.setAttribute(key, value);
    }

    /**
     * 往session中存放信息
     *
     * @param request
     * @param key
     * @param value
     */
    public static void setAttribute(HttpServletRequest request, String key, Object value, int time) {

        HttpSession session = request.getSession(true);
        session.setAttribute(key, value);
        session.setMaxInactiveInterval(time);
    }

    /**
     * 清除session中存放信息
     *
     * @param request
     * @param key
     */
    public static void removeAttribute(HttpServletRequest request, String key) {

        HttpSession session = request.getSession(true);
        session.removeAttribute(key);
    }

    /**
     * 清除session中存放信息
     *
     * @param request
     */
    public static SysUser getUserSession(HttpServletRequest request) {

        HttpSession session = request.getSession(true);
        return (SysUser) session.getAttribute(Constants.SESSION_KEY);
    }

}
